package gee

import (
	"fmt"
	"net/http"
)

// HandlerFunc 请求处理函数
type HandlerFunc func(w http.ResponseWriter, req *http.Request)

// Engine http请求的处理器， router为路由表
type Engine struct {
	router map[string]HandlerFunc
}

// New 初始化Engine
func New() *Engine {
	return &Engine{router: make(map[string]HandlerFunc)}
}

// addRoute 新增一个路由，将一个key索引到一个handler函数
func (engine *Engine) addRoute(method string, pattern string, handler HandlerFunc) {
	key := method + "-" + pattern
	engine.router[key] = handler
}

// GET 封装新增GET类型请求的路由
func (engine *Engine) GET(pattern string, handler HandlerFunc){
	engine.addRoute("GET", pattern, handler)
}

// POST 封装新增POST类型请求的路由
func (engine *Engine) POST(pattern string, handler HandlerFunc){
	engine.addRoute("POST", pattern, handler)
}

// Run 启动接口请求监听
func (engine *Engine) Run(addr string) (err error) {
	return http.ListenAndServe(addr, engine)
}

// ServeHTTP ListenAndServe的第二个参数需要重写的方法，在收到请求后，会调用请求处理器的该方法
func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	key := req.Method + "-" + req.URL.Path
	if handler, ok := engine.router[key]; ok {
		handler(w, req)
	} else {
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(w, "404 NOT FOUND: %s\n", req.URL.Path)
	}
}